package com.ruoyi.common.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname DatabaseMetaInfo
 * @Description 获取数据库信息
 * @Date 2025/11/20 16:05
 * @Created by 陈九常
 */
@Component
public class DatabaseMetaInfo {

    @Autowired
    private DataSource dataSource;

    /**
     * 通过JDBC元数据获取数据库信息
     */
    public Map<String, String> getDatabaseMetaInfo() {
        Map<String, String> info = new HashMap<>();

        try (Connection connection = dataSource.getConnection()) {
            DatabaseMetaData metaData = connection.getMetaData();

            // 获取数据库产品名称
            String databaseProductName = metaData.getDatabaseProductName();
            info.put("productName", databaseProductName);
            info.put("productVersion", metaData.getDatabaseProductVersion());
            info.put("driverName", metaData.getDriverName());
            info.put("driverVersion", metaData.getDriverVersion());

            // 获取数据库名称（catalog）
            String catalog = connection.getCatalog();
            info.put("databaseName", catalog);

            // 标准化数据库类型
            String databaseType = normalizeDatabaseType(databaseProductName);
            info.put("databaseType", databaseType);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return info;
    }

    private String normalizeDatabaseType(String productName) {
        if (productName == null) return "Unknown";

        String lowerName = productName.toLowerCase();
        if (lowerName.contains("mysql")) return "MySQL";
        if (lowerName.contains("postgresql")) return "PostgreSQL";
        if (lowerName.contains("sql server")) return "SQL Server";
        if (lowerName.contains("oracle")) return "Oracle";
        if (lowerName.contains("db2")) return "DB2";
        if (lowerName.contains("h2")) return "H2";
        if (lowerName.contains("derby")) return "Derby";
        if (lowerName.contains("sqlite")) return "SQLite";
        if (lowerName.contains("达梦") || lowerName.contains("dm")) return "达梦";
        if (lowerName.contains("kingbase") || lowerName.contains("金仓")) return "人大金仓";

        return productName;
    }
}
